package pers.mtx.hmw.controller;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import pers.mtx.hmw.cache.SingleMap;
import pers.mtx.hmw.cache.SingleTkMap;
import pers.mtx.hmw.entity.Users;
import pers.mtx.hmw.service.UsersService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
public class LoginController {


    @Autowired
    UsersService usersService;



    @Data
    static class loginReq{
        String username;
        String pwd;
    }
    @Data
    @AllArgsConstructor
    static class loginRes{
        String tk;
        boolean log;
        Users user;
    }
    @PostMapping("/login")
    public loginRes login(@RequestBody loginReq loginReq, HttpServletRequest request){
//        System.out.println(loginReq.toString());
        HttpSession sessoin=request.getSession();
        UUID uuid = UUID.randomUUID();
        String uuidAsString = uuid.toString();
        Users users = usersService.checkUser(loginReq.username, loginReq.pwd);
        SingleTkMap.getInstance().getMap().put(uuidAsString,users);
        loginRes rs;
        if (users==null){
            rs = new loginRes("",false,null);
        }else {
            rs = new loginRes(uuidAsString,true,users);
            SingleMap.getInstance().getMap().put(sessoin.getId(),users.getId());
        }
        return rs;
    }
}
